//
//  NetworkTools.swift
//  AFN Swift
//
//  Created by 王璐 on 2017/4/20.
//  Copyright © 2017年 wl. All rights reserved.
//

import UIKit
import AFNetworking

enum WLRequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    let appKey = "3500148710"
    let appSecret = "ac52bd6382fc475a644445f741e9c38b"
    let redlrectUrl = "http://www.baidu.com"
    
    
    //单例
    static let sharedTools :NetworkTools = {
        let tools = NetworkTools()
        
        //设置AFN网络请求超时
        tools.requestSerializer.timeoutInterval = 15
        
        //设置反序列化格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //将JSON中的NULL值过滤,有些第三方框架,在做字典转模型时,如果遇到 NULL值会崩溃
        (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        
        //启动连接状态监听
        tools.reachabilityManager.startMonitoring()
        
        //设置连接状态变化回调
        //        tools.reachabilityManager.setReachabilityStatusChange({ (status) in
        //             print("网络连接状态\(status)")
        //        })
        
        return tools
    }()
    
    deinit {
        reachabilityManager.stopMonitoring()
    }
    
    var reachable : Bool {
        return reachabilityManager.isReachable
    }
    
    func request(method:WLRequestMethod,urlString:String,parameters:[String:AnyObject]?,finished:@escaping (_ result: [String:AnyObject]?)->())  {
        let success={(task:URLSessionDataTask,responseObject: Any?) in
            
            if let result = responseObject as? [String:AnyObject]{
                
                finished(result)
                
            }else{
                
                print("数据格式错误")
                finished(nil)
            }
            
        }
        
        let failure = {(task:URLSessionDataTask?, error:Error) -> Void in
            print("网络请求错误\(error)")
            
            finished(nil)
        }
        
        if method == .GET {
            
            get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }
        
        //        get(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
        //
        //            if let result = responseObject as? [String:AnyObject]{
        //
        //                finished(result)
        //            }else{
        //
        //                print("数据格式错误")
        //                finished(nil)
        //            }
        //
        //
        //        }) { (_, error) in
        //            
        //            print("网络请求错误\(error)")
        //            
        //            finished(nil)
        //        }
    }
    
    
}
